# -*- coding:utf-8 -*-
# @File    : startup.py
# ***********************
import os
import sys
import pytest
import logging
from config import *
import os,json
from pytest_jsonreport.plugin import JSONReport


plugin=JSONReport()
def pytest_collection_modifyitems(items):
    print('pytest 收集到的所有测试用例：\n',items)

if __name__ == '__main__':
    from comm.script import writeLogs, writeCase,js
    # try:
    #     path = r"D:\接口\BffTesting\分析云自动化\analyCloud\report"
    #     file = os.listdir(path)
    #     for i in file:
    #         if i.endswith('.txt'):
    #             os.remove(path+'\\'+i)
    # except:
    #     pass

    # 开启日志记录(默认logs目录)
    writeLogs.MyLogs(ROOT_DIR+'logs')
    project_dir = ROOT_DIR+PROJECT_NAME
    if not os.path.isdir(project_dir):
        os.makedirs(project_dir)
        os.makedirs(project_dir+"/data")
        os.makedirs(project_dir + "/page")
        logging.info("根据配置文件，自动生成了项目目录！{}".format(project_dir))
        sys.exit(0)
    elif not os.path.isdir(project_dir+"/data"):
        os.makedirs(project_dir + "/data")
        logging.info("根据配置文件，自动生成了用例原始数据目录！{}".format(project_dir + "/data"))
        sys.exit(0)
    elif not os.path.isdir(project_dir + "/page"):
        logging.info("根据配置文件，自动生成了用例yaml文件目录！{}".format(project_dir + "/page"))


    #防止指定目录写错
    if RC['scan_dir'] != None:
        if "page" in RC['scan_dir']:
            DIR = "/"+str(RC['scan_dir']).replace(" ","").split("page")[1]
        else:
            DIR = "/"+RC['scan_dir']
    else:
        DIR = ""
    # 判断运行模式
    if RC['auto_switch'] == 3:
        logging.info("根据接口抓包数据，自动生成yaml测试用例和py测试脚本，但不运行测试！")
        if not RC['scan_dir']:
            RC['scan_dir'] = PAGE_DIR
        writeCase.write_case(PAGE_DIR+DIR, auto_yaml=True)
        sys.exit(0)

    elif RC['auto_switch'] == 2:
        if not RC['scan_dir']:
            RC['scan_dir'] = PAGE_DIR
        logging.info("根据接口抓包数据，自动生成测试yaml用例,不会运行！")
        writeCase.write_case(PAGE_DIR+DIR, auto_yaml=True,auto_py=True)
        sys.exit(0)

    elif RC['auto_switch'] == 1:
        # 如果扫描路径为空在则取项目page目录
        if not RC['scan_dir']:
            RC['scan_dir'] = PAGE_DIR
        logging.info("根据yaml用例，自动生成测试脚本，不会运行用例！")

        writeCase.write_case(PAGE_DIR+DIR, auto_yaml=False)
        sys.exit(0)
    elif RC['auto_switch'] == 0:
        try:
            if not PJ[PROJECT_NAME][RC['run_evn']]:
                logging.error("run_evn运行环境不存在！")
                sys.exit(0)
        except:
            logging.error("run_evn运行环境不存在！")
            sys.exit(0)
        logging.info("不开启自动生成测试用例功能，将直接运行测试！")

    else :
        try:
            if not PJ[PROJECT_NAME][RC['run_evn']]:
                logging.error("run_evn运行环境不存在！")
                sys.exit(0)
        except:
            logging.error("run_evn运行环境不存在！")
            sys.exit(0)
        logging.info("不开启自动生成测试用例功能，将执行自己的前置脚本后直接运行测试！")
        #分析云使用
        try:
            logging.info("分析云开始清理指定日期的数据库数据！")
            js.cleanSql()
            logging.info("分析云的数据库数据清理成功！")
        except :
            logging.info("分析云清理数据失败！")
            pass


    # 定义运行参数
    if not RC['scan_dir']:
        _TEST_DIR = TEST_DIR
    else:
        _TEST_DIR = project_dir +"/testcase/"+ str(RC['scan_dir'])

    priv_evn = ["VK","JD"]
    if EVN in priv_evn:
        if RC['scan_dir']:
            if RC["case_name"]:
                k = RC["case_name"]
            else:
                k = "test_pc"
        else:
            k = "test_pc"
    else:
        if RC['scan_dir']:
            if RC["case_name"]:
                k = RC["case_name"]
            else:
                k = ""
        else:
            k = ""
    # k = 'test_003_sales_user_delete'
    if "." in k:
        k = k.split(".")[0].replace(" ","")

    args_list = ['-vs', _TEST_DIR,
                 '-k',k,
                 # '-n', str(RC['process']),
                 '--reruns', str(RC['reruns']),
                 '--maxfail', str(RC['maxfail']),
                 '--alluredir', REPORT_DIR+'/xml',
                 '--clean-alluredir',
                 '--disable-warnings']
    # 判断是否开启用例匹配
    if RC['pattern']:
        args_list += ['-k ' + str(RC['pattern'])]
    test_result = pytest.main(args_list, plugins=[plugin])


    # 生成allure报告
    cmd = 'allure generate --clean %s -o %s ' % (REPORT_DIR+'/xml',REPORT_DIR+'/html')
    os.system(cmd)
    summary = plugin.report.get("summary")
    passed = summary.get("passed")
    failed = summary.get("failed")
    total = summary.get("total")
    passed = passed if passed else 0
    failed = failed if failed else 0
    total = total if total else 0
    import time
    fileName = str(time.time())[0:10]
    with open(REPORT_DIR+'/{}.txt'.format(fileName),'w') as f:
        f.write("{}|{}|{}".format(passed,failed,total))
        f.close()

    #云盾平台操作
    if RC['atmp'] == 0:
        jsonDir = REPORT_DIR + '/html/data/test-cases'
        atpmConfigPath = REPORT_DIR + '/atmpTemp'
        fileList = os.listdir(jsonDir)
        tc_list = []
        for jsfile in fileList:
            p = jsonDir + '/' + jsfile
            with open(p, encoding='utf-8') as f:
                c = f.read()
                f.close()
            d = json.loads(c)
            name = '  ' + d["name"] + ': []'
            tc_list.append(name)
        if not os.path.exists(atpmConfigPath):
            os.makedirs(atpmConfigPath)
        atpmfile = atpmConfigPath + '/atmpCaseConfig.yml'
        with open(atpmfile, 'w') as f:
            f.write('result_type: bfftesting,\ntc_list: \n')
            for tc in tc_list:
                f.write(tc + '\n')
    elif RC['atmp'] == 1:
        from comm.unit.reportAtmp import reportCaseJson
        reportCaseJson()

    # 上报测试结果
